﻿namespace ICP.CustomRouting
{
    using System.Collections.Generic;
    using System.Linq;
    using System.Web.Routing;

    /// <summary>
    /// Extend RouteCollection to support using CustomRoute
    /// </summary>
    public static class CustomRouteCollectionExtensions
    {
        /// <summary>
        /// Create an instance of CustomRoute and register it in the given route collection
        /// </summary>
        public static Route MapRoute(this RouteCollection routes, string name, string url, object defaults, string[] lookupParameters, IRouteValueLookupService lookupService)
        {
            CustomRoute route = new CustomRoute(url, new CustomMvcRouteHandler()
            {
                RouteValueService = lookupService
            });

            if (defaults != null)
            {
                route.Defaults = CreateRouteValueDictionary(defaults);
            }

            if (lookupParameters != null)
            {
                route.OptionalParameters = lookupParameters.ToList();
            }

            routes.Add(name, route);

            return route;
        }

        /// <summary>
        /// Create an instance of CustomRoute and register it in the given route collection
        /// </summary>
        public static CustomRoute MapReplaceableRoute(this RouteCollection routes, string name, string url, object defaults)
        {
            CustomRoute route = new CustomRoute(url, new CustomMvcRouteHandler()
            {
            });

            if (defaults != null)
            {
                route.Defaults = CreateRouteValueDictionary(defaults);
            }

            routes.Add(name, route);

            return route;
        }


        private static RouteValueDictionary CreateRouteValueDictionary(object values)
        {
            var dictionary = values as IDictionary<string, object>;
            if (dictionary != null)
            {
                return new RouteValueDictionary(dictionary);
            }

            return new RouteValueDictionary(values);
        }
    }
}
